import React, { Component } from 'react';
// 引入编辑器样式
import 'braft-editor/dist/index.css';
// 引入取色器
import 'braft-extensions/dist/color-picker.css';
// 引入编辑器组件
import BraftEditor from 'braft-editor'
import ColorPicker from 'braft-extensions/dist/color-picker';
// 引入默认值
import { defaultValue } from "./js/defaultValue";
// 需要自己添加的样式
import styles from "./css/EditDraftEditorComponents.module.css";
// Markdown转换
import Markdown from 'braft-extensions/dist/markdown'
// 表格
import 'braft-extensions/dist/table.css';
import Table from 'braft-extensions/dist/table';
const optionsTable = {
    defaultColumns: 3, // 默认列数
    defaultRows: 3, // 默认行数
    withDropdown: true, // 插入表格前是否弹出下拉菜单
    exportAttrString: '', // 指定输出HTML时附加到table标签上的属性字符串
}
const optionsColorPicker = {
    theme: 'light', // 指定取色器样式主题，支持dark和light两种样式
};

class EditDraftEditorComponents extends Component {
    constructor(props) {
        super(props);
        this.state = {
            defaultValue: BraftEditor.createEditorState(defaultValue),
            context: BraftEditor.createEditorState(''),
            extendControls: [
                {
                    key: 'custom-button',
                    type: 'button',
                    text: '预览',
                    title: '预览',
                    onClick: this.preview
                }
            ]
        }
    }

    componentWillMount() {
        console.log('componentWillMount');
        BraftEditor.use(Table(optionsTable))
        BraftEditor.use(ColorPicker(optionsColorPicker))
        BraftEditor.use(Markdown());
    }
    componentDidMount() {
        console.log('this.state.defaultValue', this.state.defaultValue.toHTML());
        // this.setState({
        //     defaultValue: BraftEditor.createEditorState(defaultValue),
        //     context: BraftEditor.createEditorState(defaultValue),
        // })
    }
    handleEditorChange = (context) => {
        console.log('str', context.toHTML());
        // this.setState({
        //     context,
        // });
    }

    submitContent = () => {
        console.log('submitContent');
    }


    preview = () => {
        console.log('preview');
        console.log(this.state.context.toHTML());
        if (window.previewWindow) {
            window.previewWindow.close();
        }
        window.previewWindow = window.open();
        window.previewWindow.document.write(this.state.context.toHTML());
        window.previewWindow.document.close();
    }

    // 上传操作
    UploadFn = (param) => {
        console.log('UploadFn');
        const serverURL = `http://10.1.70.62:8000/uploadImg/uploadImg`;
        console.log(serverURL);
        const xhr = new XMLHttpRequest();
        const fd = new FormData()

        const successFn = (response) => {
            console.log(response);
            console.log(xhr);
            // 假设服务端直接返回文件上传后的地址
            // 上传成功后调用param.success并传入上传后的文件地址
            const data = JSON.parse(xhr.response)
            param.success({
                url: data.url,
                meta: {
                    id: data.url,
                    title: data.url,
                    alt: data.url,
                    loop: true, // 指定音视频是否循环播放
                    autoPlay: true, // 指定音视频是否自动播放
                    controls: true, // 指定音视频是否显示控制栏
                    poster: data.url, // 指定视频播放器的封面
                }
            })
        }

        const progressFn = (event) => {
            // 上传进度发生变化时调用param.progress
            param.progress(event.loaded / event.total * 100)
        }

        const errorFn = (response) => {
            // 上传发生错误时调用param.error
            param.error({
                msg: 'unable to upload.'
            })
        }
        xhr.upload.addEventListener("progress", progressFn, false)
        xhr.addEventListener("load", successFn, false)
        xhr.addEventListener("error", errorFn, false)
        xhr.addEventListener("abort", errorFn, false)
        fd.append('file', param.file)
        xhr.open('POST', serverURL, true)
        xhr.send(fd)
    }

    render() {
        const { defaultValue, context, extendControls } = this.state;
        return (
            <div id="EditDraftEditorComponents">
                <p>table更新带有回车的时候可能报错，而且初始化的时候也会加载有问题</p>
                <div className={styles.EditDraftEditorComponents}>
                    <BraftEditor
                        id="EditDraftEditor"
                        defaultValue={defaultValue}
                        value={context}
                        extendControls={extendControls}
                        onChange={(str) => this.handleEditorChange(str)}
                        onSave={this.submitContent}
                        UploadFn={this.UploadFn}
                        media={{ uploadFn: this.UploadFn }}
                        contentStyle={{ height: '500px' }}
                    />
                </div>
            </div>
        );
    }
}

export default EditDraftEditorComponents;